package com.ruiysoft.service.mdse.impl;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.ruiysoft.conf.mq.MdseMqConfig;
import com.ruiysoft.entity.mdse.MerchandiseSku;
import com.ruiysoft.service.mdse.IMerchandiseManage;
import com.ruiysoft.service.mdse.IMerchandiseSkuService;
import com.ruiysoft.service.mdse.bean.MerchandiseStoceEnvelope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

@Component
public class MerchandiseStockSubscribe  {


	private Logger logger  = LoggerFactory.getLogger(getClass());
	@Resource
    private IMerchandiseManage merchandiseManage;
	@Resource
	private IMerchandiseSkuService skuService;
	@RabbitListener(
			bindings = @QueueBinding(
					value = @Queue(value = MdseMqConfig.MDSE_QUANTITY_QUEUE, durable = "true", autoDelete="false"),
					exchange = @Exchange(value = MdseMqConfig.MDSE_QUANTITY_EXCHANGE, type = ExchangeTypes.DIRECT),
					key = MdseMqConfig.MDSE_QUANTITY_BIND_KEY)
	)
	public void onMessage(Message message, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag, Channel channel) throws IOException {
//		try{
//		logger.info("扣减库存消息处理--{}",message);
			String jsonString = new String(message.getBody());
			MerchandiseStoceEnvelope envelope = JSON.parseObject(jsonString,MerchandiseStoceEnvelope.class);
			MerchandiseSku sku = new MerchandiseSku();
			sku.setSkuId(envelope.getSkuId());
			sku.setQuantity(merchandiseManage.findMdseSkuStockBySkuId(envelope.getSkuId()));
			skuService.updateById(sku);
			channel.basicAck(deliveryTag, false);
//		}catch(Throwable e){
//			logger.error("库存更新异常", e);
//		}

	}
}
